package cn.broadsense.common.jackson;

import cn.broadsense.common.annotation.LongToString;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
import java.util.Objects;

/**
 * @author: pengxin
 * @create: 2024-11-01 18:18
 * @Version 1.0
 **/
public class LongToStringSerialize extends JsonSerializer<Long> implements ContextualSerializer {

    @Override
    public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (Objects.nonNull(value)) {
            gen.writeString(String.valueOf(value));
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        LongToString annotation = property.getAnnotation(LongToString.class);
        if (Objects.nonNull(annotation) ) {
            return this;
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}
